package com.itheima.service.db.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.db.*;
import com.itheima.mapper.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TestSoulServiceImpl implements TestSoulService {

    @Autowired
    private TopicMapper topicMapper;
    @Autowired
    private TopicQuestionMapper topicQuestionMapper;
    @Autowired
    private OptionMapper optionMapper;
    @Autowired
    private UserTopicMapper userTopicMapper;
    @Autowired
    private TopicResultMapper topicResultMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    //查询问卷
    @Override
    public List<TopicVo> queryTestSoul(Long userId) {

        // 1.查询问卷
        LambdaQueryWrapper<Topic> topicLambdaQueryWrapper = new LambdaQueryWrapper<>();
        topicLambdaQueryWrapper.eq(Topic::getDr, 0);
        List<Topic> topics = topicMapper.selectList(topicLambdaQueryWrapper);

        // 2.查询问题
        List<Long> topicIdList = topics.stream().map(Topic::getId).collect(Collectors.toList());
        LambdaQueryWrapper<TopicQuestion> topicQuestionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        topicQuestionLambdaQueryWrapper.in(TopicQuestion::getTopicId, topicIdList);
        List<TopicQuestion> topicQuestions = topicQuestionMapper.selectList(topicQuestionLambdaQueryWrapper);

        // 3.查询选项
        List<Long> questionIdList = topicQuestions.stream().map(TopicQuestion::getId).collect(Collectors.toList());
        LambdaQueryWrapper<Option> optionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        optionLambdaQueryWrapper.in(Option::getQuestionId, questionIdList);
        List<Option> options = optionMapper.selectList(optionLambdaQueryWrapper);

        //4.查询锁状态
        Integer number = userTopicMapper.selectCount(new LambdaQueryWrapper<UserTopic>().eq(UserTopic::getUserId, userId));

        // 5.封装结果
        // 5.1.选项封装到QuestionVo中
        List<QuestionsVo> questionsVos = new ArrayList<>(topicQuestions.size());

        Map<Long,List<OptionsVo>> optionsVoMap = new HashMap<>();

        options.forEach(option -> {
            List<OptionsVo> optionsVos = optionsVoMap.get(option.getQuestionId());
            if (optionsVos == null) {
                optionsVos = new ArrayList<>();
                optionsVoMap.put(option.getQuestionId(), optionsVos);
            }
            optionsVos.add(new OptionsVo(option.getId().toString(), option.getContent()));
        });

        topicQuestions.forEach(topicQuestion -> {
            QuestionsVo questionsVo = new QuestionsVo(topicQuestion.getId().toString(), topicQuestion.getContent(), optionsVoMap.get(topicQuestion.getId()));
            questionsVos.add(questionsVo);
        });

        // 5.2.属性拷贝
        List<TopicVo> topicVos = new ArrayList<>(topics.size());

        topics.forEach(topic -> {
            TopicVo topicVo = new TopicVo();
            BeanUtils.copyProperties(topic, topicVo);
            topicVos.add(topicVo);
        });

        // 5.3.问题封装到TopicVo中
        Map<Long, List<QuestionsVo>> questionsVoMap = new HashMap<>();

        for (int i = 0; i < questionsVos.size(); i++) {
            List<QuestionsVo> questionsVos1 = questionsVoMap.get(topicQuestions.get(i).getTopicId());
            if (questionsVos1 == null) {
                questionsVos1 = new ArrayList<>();
                questionsVos1.add(questionsVos.get(i));
            } else {
                questionsVos1.add(questionsVos.get(i));
            }
            questionsVoMap.put(topicQuestions.get(i).getTopicId(), questionsVos1);
        }

        topicVos.forEach(topicVo -> {
            topicVo.setQuestions(questionsVoMap.get(topicVo.getId()));
            if (number == 0) {
                if (topicVo.getId() == 1) {
                    topicVo.setIsLock(0);
                } else {
                    topicVo.setIsLock(1);
                }
            }
            if (number == 1) {
                if (topicVo.getId() == 1 || topicVo.getId() == 2) {
                    topicVo.setIsLock(0);
                } else {
                    topicVo.setIsLock(1);
                }
            }
            if (number == 2) {
                if (topicVo.getId() == 1 || topicVo.getId() == 2 || topicVo.getId() == 3) {
                    topicVo.setIsLock(0);
                } else {
                    topicVo.setIsLock(1);
                }
            }
        });

        return topicVos;
    }

    //提交问卷
    @Override
    public Long saveTestSoul(AnswersVo answersVo, Long userId) {

        //用户问卷的得分、各维度的占比、是否解锁问卷、性格测试结果id
        List<String> optionIds = answersVo.getAnswers().stream().map(Answers::getOptionId).collect(Collectors.toList());
        List<Long> optionIdList = optionIds.stream().map(Long::parseLong).collect(Collectors.toList());

        // 1. 查询每道题得分分数
        List<Option> options = optionMapper.selectBatchIds(optionIdList);

        // 2.计算总分
        int totalScore = 0;
        for (Option option : options) {
            totalScore += Integer.parseInt(option.getScore());
        }
        Long resultId = 0L;
        if (totalScore <21) {resultId = 1L;}
        if (totalScore >=21 && totalScore <=40) {resultId = 2L;}
        if (totalScore >=41 && totalScore <=55) {resultId = 3L;}
        if (totalScore >=56) {resultId = 4L;}

        // 3.查询问题信息
        List<String> questionIds = answersVo.getAnswers().stream().map(Answers::getQuestionId).collect(Collectors.toList());
        List<Long> questionIdList = questionIds.stream().map(Long::parseLong).collect(Collectors.toList());
        List<TopicQuestion> questions = topicQuestionMapper.selectBatchIds(questionIdList);

        // 4.查询每道题最高分数
        List<Option>  optionScoreMaxs =  optionMapper.queryScoreMaxByQuestionId(questionIdList);
        //options,questions,optionScoreMaxs

        // 5.每种维度总得分，总最高分
        Map<Integer, Integer> totleScoreMap= new HashMap<>(4);
        Map<Integer, Integer> totleMaxScoreMap= new HashMap<>(4);
        if (questions != null && questions.size() > 0) {
            questions.forEach(question -> {
                Integer type = Integer.parseInt(question.getCharacterType());
                if(totleScoreMap.containsKey(type)){
                    options.forEach(option -> {
                        if(option.getQuestionId().equals(question.getId())){
                            totleScoreMap.put(type, totleScoreMap.get(type) + Integer.parseInt(option.getScore()));
                        }
                    });
                }else{totleScoreMap.put(type, 0);}
                if(totleMaxScoreMap.containsKey(type)){
                    optionScoreMaxs.forEach(optionScoreMax -> {
                        if(optionScoreMax.getQuestionId().equals(question.getId())){
                            totleMaxScoreMap.put(type, totleMaxScoreMap.get(type) + Integer.parseInt(optionScoreMax.getScore()));
                        }
                    });
                }else {totleMaxScoreMap.put(type, 0);}
            });
        }

        // 6.获取用户id
        UserTopic userTopic = new UserTopic();
        userTopic.setUserId(userId);
        userTopic.setTopicId(questions.get(0).getId());
        userTopic.setIsLock("0");
        userTopic.setScore(totalScore);
        userTopic.setWx(String.valueOf(totleScoreMap.get(1)*100/totleMaxScoreMap.get(1)));//外向
        userTopic.setPd(String.valueOf(totleScoreMap.get(4)*100/totleMaxScoreMap.get(4)));//判断
        userTopic.setLx(String.valueOf(totleScoreMap.get(3)*100/totleMaxScoreMap.get(3)));//理性
        userTopic.setCx(String.valueOf(totleScoreMap.get(2)*100/totleMaxScoreMap.get(2)));//抽象
        userTopic.setResultId(resultId);

        // 7.保存用户问卷
        userTopicMapper.insert(userTopic);
        return resultId;
    }

    //查询报告
    @Override
    public ReportVo queryReport(Long id, Long userId) {
        //1.查询用户问卷
        TopicResult topicResult = topicResultMapper.selectById(id);
        //2.查询用户信息
        LambdaQueryWrapper<UserTopic> lQW = new LambdaQueryWrapper<>();
        lQW.eq(UserTopic::getResultId, id);
        List<UserTopic> userTopicList = userTopicMapper.selectList(lQW);
        List<UserInfo> userInfoList = new ArrayList<>();
        userTopicList.forEach(userTopic -> {
            UserInfo userInfo = userInfoMapper.selectById(userTopic.getUserId());
            userInfoList.add(userInfo);
        });
        List<SimilarYouVo> similarYouVos = new ArrayList<>();
        userInfoList.forEach(userInfo -> {
            SimilarYouVo similarYouVo = new SimilarYouVo((userInfo.getId()), userInfo.getAvatar());
            if (!userInfo.getId().equals(userId)) {
                similarYouVos.add(similarYouVo);
            }
        });


        //3.查询用户问卷对应的所有选项
        lQW.eq(UserTopic::getResultId, id).eq(UserTopic::getUserId, userId);
        UserTopic userTopic = userTopicMapper.selectOne(lQW);
        List<DimensionsVo> dimensionsVos = new ArrayList<>();
        dimensionsVos.add(new DimensionsVo("外向", userTopic.getWx()));
        dimensionsVos.add(new DimensionsVo("判断", userTopic.getPd()));
        dimensionsVos.add(new DimensionsVo("理性", userTopic.getLx()));
        dimensionsVos.add(new DimensionsVo("抽象", userTopic.getCx()));

        ReportVo reportVo = new ReportVo(topicResult.getCharacterType(), topicResult.getImg(),  dimensionsVos, similarYouVos);

        return reportVo;
    }
}
